package com.proactive.webapp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

import org.json.JSONException;
import org.json.JSONObject;

import com.proactive.webapp.util.entity.Facebook;

public class FacebookGraphProfile {
	
	private String accessToken;
	 
	public FacebookGraphProfile(String accessToken) { //This is a constructor
	    this.accessToken = accessToken;
	}
	public String getGraph() {
	    String graphProfile = "";
	    String graphUrl = "https://graph.facebook.com/me?" + accessToken;
	    URL url = null;
	    
	    try{
	        url = new URL(graphUrl);
	        
	        try{
	            URLConnection urlConn = url.openConnection();
	            BufferedReader reader = new BufferedReader
	            (new InputStreamReader(urlConn.getInputStream()));
	            String data;
	            StringBuffer stringbuffer = new StringBuffer();
	            while((data = reader.readLine()) != null) {
	                stringbuffer.append(data + "\n");
	            } 
	            reader.close();
	            graphProfile = stringbuffer.toString();
	        } catch (IOException e) {
	            e.printStackTrace();
	        }
	    } catch (MalformedURLException e) {
	        e.printStackTrace();
	    }
	    return graphProfile;
	}

	public Facebook getGraphProfile(String fbGraph) {
		Facebook facebook = new Facebook();
	    try {
	        JSONObject jsonObj = new JSONObject(fbGraph);
	        facebook.setId(jsonObj.getString("id"));
	        facebook.setName(jsonObj.getString("name"));
	        facebook.setEmail(jsonObj.getString("email"));
	        facebook.setVerified(jsonObj.getBoolean("verified"));
	        facebook.setPhoto("https://graph.facebook.com/"+facebook.getId()+"/picture?type=large");
	        facebook.setFacebookUrl(jsonObj.getString("link"));
	    } catch (JSONException e) {
	        e.printStackTrace();
	    }
	    return facebook;
	}
}
